<template>
  <div class="scan-input-box">
    <el-input
      ref="codeInput"
      v-model="code"
      :clearable="true"
      style="width: 400px"
      placeholder="请扫码或输入条码"
      @keyup.enter.native="sacn"
      @input="(e) => (code = validSe(e))"
    >
      <template #prepend>产品条码</template>
    </el-input>
    <el-dialog
      title="扫描从码"
      width="30%"
      v-model="dialogSubCodeVisible"
      @close="handleSubDialogClose"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div class="scan-dialog">
        <div class="info">
          <div class="name">
            产品名称：{{ productDetail && productDetail.commonName }}产品
          </div>
        </div>
        <el-input
          ref="subCodeRef"
          @keyup.enter.native="sacnSubCode"
          @input="(e) => (inputSubCode = validSe(e))"
          placeholder="请扫描从码"
          v-model="inputSubCode"
          clearable
        ></el-input>
      </div>
      <template #footer class="dialog-footer">
        <el-button @click="dialogSubCodeVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog
      title="扫描主码"
      width="30%"
      v-model="dialogMainCodeVisible"
      @close="handleMainDialogClose"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div class="scan-dialog">
        <el-input
          ref="mainCodeRef"
          @keyup.enter.native="sacnMainCode"
          @input="(e) => (inputMainCode = validSe(e))"
          placeholder="请扫描主码"
          v-model="inputMainCode"
          clearable
        ></el-input>
      </div>
      <template #footer class="dialog-footer">
        <el-button @click="dialogMainCodeVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ScanInputBox">
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  tableData: {
    type: Array,
  },
  query: {
    type: Object,
    default: undefined,
  },
  api: {
    type: Function,
  },
})
const dialogSubCodeVisible = ref(false)
const dialogMainCodeVisible = ref(false)
const inputSubCode = ref('')
const inputMainCode = ref('')
const productDetail = ref(undefined)
const code = ref('')
const mainCode = ref('')

function generateProductKey(product) {
  const key =
    product.serialNumber +
    '&' +
    product.productId +
    '&' +
    product.batchNumber +
    '&' +
    product.validityDate +
    '&' +
    product.productionDate
  product._id = key
  return product
}
function sacn() {
  if (!code.value) {
    proxy.$message({
      message: '请扫描二维码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  const params = {
    ...props.query,
    code: proxy.$fn.setTrim(code.value),
  }
  props
    .api(params)
    .then((res) => {
      if (res && res.success) {
        if (res.data.product) {
          res.data.product.disabled = !!res.data.product.serialNumber
        }

        if (res.data.productDetail) {
          res.data.productDetail.disabled =
            !!res.data.productDetail.serialNumber
        }

        const scanState = res.data.flag
        let product = res.data.product && generateProductKey(res.data.product)
        productDetail.value = product
        // const detail = res.data.productDetail;
        const detail =
          res.data.productDetail && generateProductKey(res.data.productDetail)

        switch (scanState) {
          case 0:
            return scanResultsCode(detail)
          case 1:
            return scanProgressSub(detail)
          case 2:
            return scanProgressMain()
        }
      } else {
        code.value = ''
      }
    })
    .catch((err) => {
      code.value = ''
    })
}
function sacnSubCode() {
  if (code.value) inputMainCode.value = code.value
  const params = {
    ...props.query,
    subCode: proxy.$fn.setTrim(inputSubCode.value),
    mainCode: proxy.$fn.setTrim(inputMainCode.value),
  }
  props
    .api(params)
    .then((res) => {
      if (res && res.success) {
        if (res.data.productDetail) {
          res.data.productDetail.disabled =
            !!res.data.productDetail.serialNumber
        }

        const flag = res.data && res.data.flag
        if (flag > -1) {
          const product =
            res.data.productDetail && generateProductKey(res.data.productDetail)
          scanResultsCode(product, 'sub')
        } else {
          proxy.$message({
            message: `扫码报错！`,
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
        }
      } else {
        inputSubCode.value = ''
      }
    })
    .catch((err) => {
      inputSubCode.value = ''
    })
}
function sacnMainCode() {
  const params = {
    ...props.query,
    subCode: proxy.$fn.setTrim(code.value),
    mainCode: proxy.$fn.setTrim(inputMainCode.value),
  }
  props.api(params).then((res) => {
    if (res && res.success) {
      if (res.data.productDetail) {
        res.data.productDetail.disabled = !!res.data.productDetail.serialNumber
      }
      const flag = res.data && res.data.flag
      if (flag > -1) {
        const product =
          res.data.productDetail && generateProductKey(res.data.productDetail)
        scanResultsCode(product, 'main')
      } else {
        proxy.$message({
          message: `扫码报错！`,
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
      }
    }
  })
}
function findFroduct(data) {
  let item = props.tableData.find((row) => row._id === data._id)
  return {
    flag: !!item,
    data: item || data,
  }
}
function scanResultsCode(data, source) {
  const findFroductObj = findFroduct(data)
  inputSubCode.value = undefined
  inputMainCode.value = undefined
  dialogMainCodeVisible.value = false
  dialogSubCodeVisible.value = false
  code.value = undefined
  emits('callback', findFroductObj)
}
function scanProgressSub(data) {
  dialogSubCodeVisible.value = true
  productDetail.value = { ...data }
  let timer = setTimeout(() => {
    proxy.$refs.subCodeRef.focus()
    clearTimeout(timer)
  }, 100)
}
function scanProgressMain() {
  dialogMainCodeVisible.value = true
  let timer = setTimeout(() => {
    proxy.$refs.mainCodeRef.focus()
    clearTimeout(timer)
  }, 100)
}
function handleSubDialogClose() {
  inputSubCode.value = undefined
  inputMainCode.value = undefined
  code.value = undefined
}
function handleMainDialogClose() {
  inputSubCode.value = undefined
  inputMainCode.value = undefined
  code.value = undefined
}
</script>

<style scoped></style>
